package com.example.musicplayer

import android.animation.AnimatorInflater
import android.animation.AnimatorSet
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.example.musicplayer.dao.UserProfileDAO
import com.example.musicplayer.login.LoginActivity
import com.example.musicplayer.model.UserProfile
import com.example.musicplayer.profile.DownloadFragment
import com.example.musicplayer.profile.HistoryFragment
import com.example.musicplayer.profile.PlaylistFragment
import com.example.musicplayer.profile.settings.EditProfileActivity
import com.example.musicplayer.util.HistoryManager
import com.google.android.material.navigation.NavigationView

class ProfileFragment : Fragment() {

    private lateinit var navFavorites: Button
    private lateinit var navDownload: Button
    private lateinit var navHistory: Button
    private lateinit var messagesButton: ImageButton
    private lateinit var settingsButton: ImageButton
    private lateinit var drawerLayout: DrawerLayout
    private lateinit var navigationView: NavigationView
    private lateinit var avatarImageView: ImageView
    private lateinit var usernameTextView: TextView

    private lateinit var userProfileDAO: UserProfileDAO


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_profile, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        navFavorites = view.findViewById(R.id.nav_favorites)
        navDownload = view.findViewById(R.id.nav_download)
        navHistory = view.findViewById(R.id.nav_history)
        messagesButton = view.findViewById(R.id.messages)
        settingsButton = view.findViewById(R.id.settings)

        drawerLayout = view.findViewById(R.id.drawer_layout)
        navigationView = view.findViewById(R.id.nav_view)
        avatarImageView = view.findViewById(R.id.avatar)
        usernameTextView = view.findViewById(R.id.username)

        // 初始化 DAO
        userProfileDAO = UserProfileDAO(requireContext())

        // 设置 Drawer 监听器
        navigationView.setNavigationItemSelectedListener { item ->
            when (item.itemId) {
                R.id.edit_profile -> {
                    // 处理“编辑资料”操作
                    // 打开编辑资料页面
                    val userId = getLoggedInUserId() // 获取当前登录用户的 ID
                    val intent = Intent(requireContext(), EditProfileActivity::class.java)
                    intent.putExtra("user_id", userId)
                    startActivity(intent)
                }
                R.id.change_cover -> {
                    // 处理“更换封面”操作
                }
                R.id.privacy_settings -> {
                    // 处理“隐私设置”操作
                }
                R.id.share -> {
                    // 处理“分享”操作
                }
                R.id.logout -> {
                    // 处理“退出登录”操作
                    logoutUser()
                }
            }

            drawerLayout.closeDrawer(GravityCompat.END)
            true
        }

        // 初始化按钮状态和字体大小
        resetButtons()

        navFavorites.setOnClickListener { onButtonClicked(navFavorites, PlaylistFragment()) }
        navDownload.setOnClickListener { onButtonClicked(navDownload, DownloadFragment()) }
        navHistory.setOnClickListener { onButtonClicked(navHistory, HistoryFragment()) }

        // 设置消息图标按钮的点击监听器
        messagesButton.setOnClickListener {
            (activity as? MainActivity)?.showMessagesFullscreen()
        }

        // 设置设置图标按钮的点击监听器
        settingsButton.setOnClickListener {
            drawerLayout.openDrawer(GravityCompat.END)
        }

        // 加载用户信息
        loadUserInfo()
    }


    private fun loadUserInfo() {
        val userId = getLoggedInUserId()
        if (userId > 0) {
            val userProfile = userProfileDAO.getUserProfileById(userId)
            userProfile?.let {
                updateUI(it)
            }
        }
    }

    private fun updateUI(userProfile: UserProfile) {
        val headerView = navigationView.getHeaderView(0)
        val headerUserNameTextView = headerView.findViewById<TextView>(R.id.user_name)
        headerUserNameTextView.text = userProfile.username
        usernameTextView.text = userProfile.username
        userProfile.image?.let {
            // 如果头像是 Blob 数据，需要将其转换为 Bitmap 并显示
            val bitmap = BitmapFactory.decodeByteArray(it, 0, it.size)
            avatarImageView.setImageBitmap(bitmap)
        }
    }

    private fun onButtonClicked(button: Button, fragment: Fragment) {
        // 重置所有按钮的状态
        resetButtons()

        // 设置点击的按钮为选中状态并播放动画
        selectButton(button)
        showContentFragment(fragment)
    }

    private fun resetButtons() {
        navFavorites.isSelected = false
        navDownload.isSelected = false
        navHistory.isSelected = false

        // 设置初始字体大小
        navFavorites.textSize = 14f
        navDownload.textSize = 14f
        navHistory.textSize = 14f
    }

    private fun selectButton(button: Button) {
        button.isSelected = true

        // 播放字体大小变化动画
        val animator = AnimatorInflater.loadAnimator(requireContext(), R.animator.button_text_size_animator) as AnimatorSet
        animator.setTarget(button)
        animator.start()
    }

    private fun showContentFragment(fragment: Fragment) {
        val fragmentManager: FragmentManager = childFragmentManager
        val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()
        fragmentTransaction.replace(R.id.content_container, fragment)
        fragmentTransaction.addToBackStack(null) // 可选：将事务添加到返回栈
        fragmentTransaction.commit()
    }

    private fun clearLoginState() {
        val sharedPreferences = requireActivity().getSharedPreferences("UserPrefs", 0) // 使用0作为默认的MODE_PRIVATE模式
        val editor = sharedPreferences.edit()
        editor.remove("isLoggedIn") // 清除登录状态
        editor.clear() // 清除所有数据（如果需要的话）
        editor.apply()
    }

    private fun logoutUser() {
        clearLoginState()
        context?.let { HistoryManager.clearHistory(it) }

        // 启动登录页面
        val intent = Intent(requireContext(), LoginActivity::class.java)
        startActivity(intent)

        // 结束当前活动，防止用户通过返回键回到主页面
        requireActivity().finish()
    }

    private fun getLoggedInUserId(): Int {
        val sharedPreferences = requireActivity().getSharedPreferences("UserPrefs", 0)
        return sharedPreferences.getInt("user_id", 0) // 默认值为0，表示未登录
    }
}